package com.woc.cloud.admin.controller;

import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.servlet.ModelAndView;

import com.woc.cloud.admin.constant.ServiceUrl;
import com.woc.cloud.admin.entity.Response;

/**
 * 登录认证
 * 
 * @author     woc
 * @date       2024-01-26 
 * @version    0.0.1
 */
@RestController
@RequestMapping(value = "/auth")
public class AuthController {
	
	@Autowired
    private RestTemplate restTemplate;

    @RequestMapping(value = {"/login"}, method = RequestMethod.GET)
    public Object login() {
        ModelAndView mav = new ModelAndView();
        mav.setViewName("auth/login");
        return mav;
    }

    @SuppressWarnings("unchecked")
	@RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public Object login(@RequestParam(required = true) String name,
                       @RequestParam(required = true) String password,
                       HttpServletRequest request) {
    	String url = ServiceUrl.AUTH_LOGIN + "?name=" + name;
    	url += "&password=" + password;
    	Response<Map<String, Object>> resp = restTemplate.postForObject(url, null, Response.class);
        Response<Map<String, Object>> response = new Response<Map<String, Object>>();
        if (!resp.isOk()) {
            return response.withError("登录失败");
        }
        HttpSession session = request.getSession();
        if (session == null) {
            return response.withError("登录失败");
        }
        Map<String, Object> res = resp.getData();
        session.setAttribute("userName", res.get("userName"));
        session.setAttribute("userPerm", res.get("userPerm"));
        return response.withOk();
    }

    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public Object logout(HttpServletRequest request) {
        Response<String> response = new Response<String>();
        HttpSession session = request.getSession();
        if (session == null) {
            return response.withError("注销失败");
        }
        session.removeAttribute("userName");
        session.removeAttribute("userPerm");
        return response.withOk("注销成功");
    }

}
